import file from '@system.file';
import request from '@ohos.request';
import fetch from '@system.fetch';
import router from '@system.router';
import prompt from '@system.prompt';
import geolocation from '@system.geolocation';
import Service from '../../generated/TestService.js';
import dataStorage from '@ohos.data.storage'
import mediaLibrary from '@ohos.multimedia.mediaLibrary';
import featureAbility from '@ohos.ability.featureAbility';
import http from '@ohos.net.http';

export default {
    data: {
        lable:'homepage日志',
//        页面
        flag: 1,
        oneFlag: 1,
        twoFlag: 2,
        threeFlag: 3,
        fourFlag: 4,
        fiveFlag: 5,
        icon: {
            community: '/common/nav/community.png',
            message: '/common/nav/message.png',
            mine: '/common/nav/mine.png',
            skate: '/common/nav/skate.png',
            video: '/common/nav/video.png'
        },
        iconImageFlag: 1,
        skatebottonvalue:'开始',
        options : {
            duration: 500,
        },
        frames : [
            {
                width:70,height:70,offset:0.0
            },
            {
                width:80,height:60,offset:0.2
            },
            {
                width:60,height:80,offset:0.4
            },
            {
                width:75,height:65,offset:0.6
            },
            {
                width:65,height:75,offset:0.8
            },
            {
                width:70,height:70,offset:1.0
            },
        ],

        articles :null,
//        swiper位置
        index:0,
        myindex:0,
        videolist:null,
        videodirection:'',

        sessions:[],
//        视频
//        curvideoName:null,
        event:'',
        seekingtime:'',
        timeupdatetime:'',
        seekedtime:'',
        isStart: false,
        isfullscreenchange: false,
        duration: '',
        //为视频链接地址作为组件id
        videoid:'',
        hour:0,
        minute:0,
        second:0,
        modeFlag: "full",
        hearten:'/common/picture/hearten.png',
        paneltype:'',
        videocomments:[],
        myvideocomment:null,
        uploadvideoid:null,
//        滑板
        skating: false,
        skateicon:'/common/picture/startskate.png',
        timer:'',
        decodetimer:'',
        //转换坐标系的
        ll:'经纬度',
        //ll 逆编码地址
        location:'地址',
        //获取原始经纬度
        latitude:'纬度',
        longitude:'经度',
        mycode:'code',
        echo:'',
        locationdata:'定位信息',
        types:'',
        skatepopup:false,
        parks:null,
        tripid:null,
        lasttripid:null,
        //headicon:'http://101.35.82.76:9001/file/picture?name=wutiaowu.png',
//        system
        context:'',
        cachepath:'',
        picturename:'picture',
        utilInterface:null,
        path:'',
        //mine
        username:'未登录',
        userid:'-1',
        headshot:'/common/picture/initheadshot.png',
        myvideos:[],
        myfollows:[],
        myarticles:[],
    },
    async onInit() {
        if(this.userid === '-1'){
            this.LoadVideo();
        }

        this.echo = new Service(); // 此处新建FA实例
        this.context = featureAbility.getContext();
        this.path = await this.context.getFilesDir()

//        this.LoadArticle();

        this.subscribe();

        this.decodetimer = setInterval(()=>{
            this.LLtransffer();
            if(this.ll!=='经纬度'){
                this.gaodedecode();
            }
        },10000);
    },
    onDestroy(){
      this.unsubscribe();
    },
    async onShow(){
//        this.LoadVideo();
        this.LoadParks();
        this.LoadArticle();
        var context = featureAbility.getContext()
        var path = await context.getFilesDir()
        let storage = dataStorage.getStorageSync(path + '/mystore')
        this.username = storage.getSync('username', '未登录')
        this.headshot = storage.getSync('headshot', '/common/picture/initheadshot.png')
        this.userid = storage.getSync('userid', '-1')

        if(this.userid!=='-1'){
            this.LoadMyArticle();
            this.LoadMyFollow()
            this.LoadMyVideo()
            this.LoadVideo();
        }
    },
    onReady(){
        this.InitLocation
    },
    PleaseLogin(){
        let storage = dataStorage.getStorageSync(this.path + '/mystore')
        this.userid = storage.getSync('userid', '-1')
        if(this.userid === '-1'){
            prompt.showToast({
                message: '请先登录'
            })
            return;
        }
    },
    detailPage(e) {
        var articleid = e.target.dataSet.articleid
        console.info(articleid)
        var article;
        for (var i = 0; i < this.articles.length; i++) {
            if(this.articles[i].articleid === articleid){
                article = this.articles[i]
            }
        }
        router.push({
            uri: "pages/articledetail/articledetail",
            params: {
                articleid:articleid,
                title:article.title,
                tags:article.tags,
                body:article.body,
                cover:article.cover,
                username:article.username,
            }
        });
    },
    SearchPage(){
        router.push({
            uri: "pages/searchpage/searchpage",
            params: {
                userid:this.userid,
            }
        });
    },
    getSessions(){
        var that = this

        let httpRequest= http.createHttp();
        httpRequest.request("http://101.35.82.76:9002/session/getownsession?"+"userid="+this.userid,
            {
                method: 'GET',
                readTimeout: 60000,
                connectTimeout: 60000
            },(err, data) => {
                if (!err) {
                    console.info('Result:' + data.result);
                    console.info('code:' + data.responseCode);
                    console.info('header:' + data.header);
                    var res = JSON.stringify(JSON.parse(data.result).data)
                    var sessions = JSON.stringify(JSON.parse(res).sessions)
                    that.sessions = JSON.parse(sessions)
                } else {
                    console.info('error:' + err.data);
                    prompt.showToast({
                        message: 'getsession Send Error'+ JSON.stringify(err)
                    })
                }
            });
    },
    chatPage(e) {
        var sessionid = e.target.dataSet.sessionid
        console.info(sessionid)
//        var that = this
        var session;
        for (var i = 0; i < this.sessions.length; i++) {
            if(this.sessions[i].sessionid === sessionid){
                session = this.sessions[i]
            }
        }
        router.push({
            uri: "pages/chatpage/chatpage",
            params: {
                sessionid:sessionid,
                sessionname:session.opname,
                lastmsg:session.lastmessage,
                opheadshot:session.opheadshot,
                headshot:this.headshot,
                userid:this.userid,
                opuserid:session.opuserid,
            }
        });
    },
    loginPage(){
        router.push({
            uri: "pages/loginpage/loginpage",
            params: {}
        });
    },
    minedetailPage(){
        router.push({
            uri: "pages/minedetailpage/minedetailpage",
            params: {}
        });
    },
    ownmainpage(msg){
        var touserid = `${msg.target.dataSet.touserid}`
        var toheadshot = `${msg.target.dataSet.toheadshot}`
        var tousername = `${msg.target.dataSet.tousername}`
        router.push({
            uri: "pages/ownmainpage/ownmainpage",
            params: {
                touserid:touserid,
                userid:this.userid,
                tousername:tousername,
                toheadshot:toheadshot,
            }
        });
    },
    //    上传
    UpVideo(){
        router.push({
            uri: "pages/uploadvideopage/uploadvideopage",
            params: {}
        });
    },
    //写文章
    WriteArticle(){
        router.push({
            uri: "pages/writearticlepage/writearticlepage",
            params: {}
        });
    },
    //地图附近的人
    mapPage(e) {
        var longitude = this.longitude
        var latitude = this.latitude
        var ll = this.ll
        router.push({
            uri: "pages/mappage/mappage",
            params: {
                longitude:longitude,
                latitude:latitude,
                ll:ll,
            }
        });
    },

    clickCommunity() {
        this.iconImageFlag = this.oneFlag;
        this.flag = this.oneFlag;
        this.$element('communityicon').animate(this.frames,this.options).play()
        this.$element(this.videoid).pause();
        this.LoadArticle();
    },
    clickVideo() {
        if(this.flag === this.twoFlag){
            this.LoadVideo();
        }else{
            if(this.videoid!==''){
                this.$element(this.videoid).start();
                this.isStart = true
            }
        }
        this.iconImageFlag = this.twoFlag;
        this.flag = this.twoFlag;
        this.$element('videoicon').animate(this.frames,this.options).play()
    },
    clickSkate() {
        this.iconImageFlag = this.threeFlag;
        this.flag = this.threeFlag;
        this.$element('skateicon').animate(this.frames,this.options).play()
        this.$element(this.videoid).pause();
//        this.getLocation();
//        this.subscribe();
    },
    clickMessage() {
        let storage = dataStorage.getStorageSync(this.path + '/mystore')
        this.userid = storage.getSync('userid', '-1')
        if(this.userid!=='-1'){
            this.getSessions()
        }
        this.iconImageFlag = this.fourFlag;
        this.flag = this.fourFlag;
        this.$element('messageicon').animate(this.frames,this.options).play()
        this.$element(this.videoid).pause();
    },
    clickMine() {
        this.iconImageFlag = this.fiveFlag;
        this.flag = this.fiveFlag;
        this.$element('mineicon').animate(this.frames,this.options).play()
        this.$element(this.videoid).pause();
        let storage = dataStorage.getStorageSync(this.path + '/mystore')
        this.userid = storage.getSync('userid', '-1')
        if(this.userid!=='-1'){
            this.LoadMyArticle();
            this.LoadMyFollow()
            this.LoadMyVideo()
        }
    },
//    文章
    LoadArticle(){
        let httpRequest= http.createHttp();
        httpRequest.request("http://101.35.82.76:9002/article/getArticle",
            {
                method: 'GET',
                readTimeout: 60000,
                connectTimeout: 60000
            },(err, data) => {
                if (!err) {
                    console.info('Result:' + data.result);
                    console.info('code:' + data.responseCode);
                    console.info('header:' + data.header);

                    var res = JSON.stringify(JSON.parse(data.result).data)
                    var articles = JSON.stringify(JSON.parse(res).articles)
                    this.articles = JSON.parse(articles)

                } else {
                    console.info('error:' + err.data);
                    prompt.showToast({
                        message: 'loadarticle Send Error'+ JSON.stringify(err)
                    })
                }
            });
    },
    LoadMyArticle(){
        let httpRequest= http.createHttp();
        httpRequest.request("http://101.35.82.76:9002/article/getMyArticle?userid="+this.userid,
            {
                method: 'GET',
                readTimeout: 60000,
                connectTimeout: 60000
            },(err, data) => {
                if (!err) {
                    console.info('Result:' + data.result);
                    console.info('code:' + data.responseCode);
                    console.info('header:' + data.header);

                    var res = JSON.stringify(JSON.parse(data.result).data)
                    var articles = JSON.stringify(JSON.parse(res).articles)
                    this.myarticles = JSON.parse(articles)

                } else {
                    console.info('error:' + err.data);
                    prompt.showToast({
                        message: 'Send Error'+ JSON.stringify(err)
                    })
                }
            });
    },
//    关注
    LoadMyFollow(){
        let httpRequest= http.createHttp();
        httpRequest.request("http://101.35.82.76:9002/follow/getMyFollow?userid="+this.userid,
            {
                method: 'GET',
                readTimeout: 60000,
                connectTimeout: 60000
            },(err, data) => {
                if (!err) {
                    console.info('Result:' + data.result);
                    console.info('code:' + data.responseCode);
                    console.info('header:' + data.header);

                    var res = JSON.stringify(JSON.parse(data.result).data)
                    var follows = JSON.stringify(JSON.parse(res).follows)
                    this.myfollows = JSON.parse(follows)

                } else {
                    console.info('error:' + err.data);
                    prompt.showToast({
                        message: 'loadmyfollow Send Error'+ JSON.stringify(err)
                    })
                }
            });
    },
    LoadMyVideo(){
        let httpRequest= http.createHttp();
        httpRequest.request("http://101.35.82.76:9002/file/getMyVideo?userid="+this.userid,
            {
                method: 'GET',
                readTimeout: 60000,
                connectTimeout: 60000
            },(err, data) => {
                if (!err) {
                    console.info('Result:' + data.result);
                    console.info('code:' + data.responseCode);
                    console.info('header:' + data.header);

                    var res = JSON.stringify(JSON.parse(data.result).data)
                    var myvideos = JSON.stringify(JSON.parse(res).myvideos)
                    this.myvideos = JSON.parse(myvideos)

                } else {
                    console.info('error:' + err.data);
                    prompt.showToast({
                        message: 'loadmyvideo Send Error'+ JSON.stringify(err)
                    })
                }
            });
    },
//    视频
    preparedCallback:function(e){ this.event = '视频连接成功'; this.duration = e.duration;},
    startCallback:function(){ this.event = '视频开始播放';},
    pauseCallback:function(){ this.event = '视频暂停播放'; },
    finishCallback:function(){ this.event = '视频播放结束';},
    errorCallback:function(){ this.event = '视频播放错误';},
    seekingCallback:function(e){ this.seekingtime = e.currenttime; },
    timeupdateCallback:function(e){ this.timeupdatetime = e.currenttime;},
    change_start_pause: function() {
        //评论区
        if(this.modeFlag === 'full' || this.modeFlag === 'mini'){
            this.modeFlag = 'close'
            this.$element('commentpanel').close()
            this.$element('sharepanel').close()
            return;
        }
        if(this.isStart) {
            this.$element(this.videoid).pause();
            this.isStart = false;
        } else {
            this.$element(this.videoid).start();
            this.isStart = true;
        }
    },
    change_fullscreenchange: function() {//全屏
        if(!this.isfullscreenchange) {
            this.$element(this.videoid).requestFullscreen({ screenOrientation : 'default' });
            this.isfullscreenchange = true;
        } else {
            this.$element(this.videoid).exitFullscreen();
            this.isfullscreenchange = false;
        }
    },
    SwiperChange(e){
        this.videoid = this.videolist[e.index].src
        this.uploadvideoid = this.videolist[e.index].videoid
        this.videocomments = this.videolist[e.index].commentInfos
        if(this.videolist[e.index].hearten === 'false'){
            this.hearten = '/common/picture/hearten.png';
        }else{
            this.hearten = '/common/picture/hadhearten.png';
        }

        console.info('当前位置'+e.index)
        console.info('当前视频'+this.videoid)

//        prompt.showToast({
//            message:this.videocomments
//        })
        this.index = e.index
        if(this.index === 0){

        }else if(this.index === this.videolist.length-1){

        }
        if(this.index > this.myindex){
            this.$element(this.videolist[this.myindex].src).pause();
            this.$element(this.videolist[this.index].src).start();
            this.myindex = this.index
        }else if(this.index < this.myindex){
            this.$element(this.videolist[this.index].src).start();
            this.$element(this.videolist[this.myindex].src).pause();
            this.myindex = this.index
        }

    },
    VideoSwitchAction(msg){
        this.videodirection = JSON.parse(JSON.stringify(msg)).direction

        if(this.index === 0 && this.videodirection === 'down'){
            this.LoadVideo()
        }
        if(this.index === this.videolist.length-1 && this.videodirection === 'up'){
            prompt.showToast({
                message:'加载更多视频'
            })
            this.AddVideo()
        }
    },
    AddVideo(){
        let httpRequest= http.createHttp();
        httpRequest.request("http://101.35.82.76:9002/file/loadMoreVideo",
            {
                method: 'GET',
                readTimeout: 60000,
                connectTimeout: 60000
            },(err, data) => {
                if (!err) {
                    console.info('Result:' + data.result);
                    console.info('code:' + data.responseCode);
                    console.info('header:' + data.header);

                    var res = JSON.stringify(JSON.parse(data.result).data)
                    var videolist = JSON.stringify(JSON.parse(res).videolist)
                    var morevideos = JSON.parse(videolist);
                    this.videolist = this.videolist.concat(morevideos)

//                    this.index = this.videolist.length;
//                    this.myindex = this.videolist.length;
//                    this.videoid = this.videolist[this.videolist.length].src
                    //                    prompt.showToast({
                    //                        message:this.videolist
                    //                    })
                } else {
                    console.info('error:' + JSON.stringify(err));
                    prompt.showToast({
                        message: 'loadmorevideo Send Error'+ JSON.stringify(err)
                    })
                }
            });
    },
    LoadVideo(){
        if(this.videoid!==null && this.videoid !==''){
            this.$element(this.videoid).pause();
            this.isStart = false
        }

        if(this.path!==''){
            let storage = dataStorage.getStorageSync(this.path + '/mystore')
            this.userid = storage.getSync('userid', '-1')
        }
        var url;
        if(this.userid!== '-1'){
            url = "http://101.35.82.76:9002/file/video?userid="+this.userid
        }else{
            url = "http://101.35.82.76:9002/file/video"
        }

        this.videolist = null;
        let httpRequest= http.createHttp();
        httpRequest.request(url,
            {
                method: 'GET',
                readTimeout: 60000,
                connectTimeout: 60000
            },(err, data) => {
                if (!err) {
                    console.info('Result:' + data.result);
                    console.info('code:' + data.responseCode);
                    console.info('header:' + data.header);
//                    if(this.videoid!==null && this.videoid !==''){
//                        this.$element(this.videoid).pause();
//                    }

                    var res = JSON.stringify(JSON.parse(data.result).data)
                    var videolist = JSON.stringify(JSON.parse(res).videolist)
                    this.videolist = JSON.parse(videolist)


                    this.index = 0;
                    this.myindex = 0;
                    this.videoid = this.videolist[0].src
                    this.uploadvideoid = this.videolist[0].videoid
                    this.videocomments = this.videolist[0].commentInfos
                    if(this.flag === this.twoFlag){
                        this.$element(this.videoid).start();
                        this.isStart = true
                    }
                    if(this.videolist[0].hearten === "false"){
                        this.hearten = '/common/picture/hearten.png'
                    }else{
                        this.hearten = '/common/picture/hadhearten.png'
                    }


//                    prompt.showToast({
//                        message:this.videolist
//                    })
                } else {
                    console.info('error:' + JSON.stringify(err));
//                    prompt.showToast({
//                        message: 'loadvideo Send Error'+ JSON.stringify(err)
//                    })
                }
            });
    },
    LoadVideoComment(){

    },
    VideoCommentChange(e){
        this.myvideocomment = e.text;
    },
    AddVideoComment(){
        var that = this;
        if(this.userid!=='-1'){
            let httpRequest= http.createHttp();
            httpRequest.request("http://101.35.82.76:9002/comment/addComment?"+'userid='+that.userid+
            '&type=video'+'&worksid='+that.uploadvideoid+'&body='+that.myvideocomment,
                {
                    method: 'GET',
                    readTimeout: 60000,
                    connectTimeout: 60000
                },(err, data) => {
                    if (!err) {
                        console.info('Result:' + data.result);
                        console.info('code:' + data.responseCode);
                        console.info('header:' + data.header);
                        //[{"body":"沙发","headshot":"http://101.35.82.76:9001/file/file/58634672-42e7-4c14-9b9d-44cc5ecfbc9a.jpg","id":"1","time":1642150288000,"type":"video","userid":"1","username":"MarsHou","worksid":"27"}]
                        function  Comment(body,headshot,username) //声明对象
                        {
                            this.body = body;
                            this.headshot= headshot;
                            this.username= username;
                        }
                        that.videocomments.push(new Comment(that.myvideocomment,that.headshot,that.username))
                        var len = that.myvideocomment.length
                        for(var i = 0; i < len; i++){
                            this.$element('videocomment').delete()
                        }
                    } else {
                        console.info('error:' + JSON.stringify(err));
                        prompt.showToast({
                            message: 'addvideocomment Send Error'+ JSON.stringify(err)
                        })
                    }
                });
        }else{
            prompt.showToast({
                message:'请先登录'
            })
        }
    },
//    视频评论面板
    changeMode(e) {
        this.modeFlag = e.mode
        if(e.mode === 'mini'){
            this.modeFlag = 'close'
            this.$element('commentpanel').close()
            this.$element('sharepanel').close()
        }
    },
//    showPanel(msg) {
//        if(msg === '评论区'){
//            this.$element('videocomment').animate(this.frames,this.options).play()
//        }else{
//            this.$element('videoshare').animate(this.frames,this.options).play()
//        }
//        this.paneltype = msg
//        this.$element('commentpanel').show()
//    },
//    closePanel() {
//        this.$element('commentpanel').close()
//    },
    showCommentPanel() {
        this.$element('commentpanel').show()
        this.modeFlag = 'full'
    },
    closeCommentPanel() {
        this.$element('commentpanel').close()
    },
    showSharePanel() {
        this.$element('sharepanel').show()
        this.modeFlag = 'full'
    },
    closeSharePanel() {
        this.$element('sharepanel').close()
    },
//    点赞
    Hearten(){
        if(this.userid === '-1'){
            prompt.showToast({
                message:'请先登录'
            })
            return;
        }
        var url;
        if(this.hearten === '/common/picture/hearten.png'){
            this.hearten = '/common/picture/hadhearten.png'
            url = "http://101.35.82.76:9002/hearten/addHearten"
        }else{
            this.hearten = '/common/picture/hearten.png'
            url = "http://101.35.82.76:9002/hearten/deleteHearten"
        }

        let httpRequest= http.createHttp();
        httpRequest.request(url+"?userid="+this.userid+"&worksid="+this.uploadvideoid+
            "&type=video",
            {
                method: 'GET',
                readTimeout: 60000,
                connectTimeout: 60000
            },(err, data) => {
                if (!err) {
                    console.info('Result:' + data.result);
                    console.info('code:' + data.responseCode);
                    console.info('header:' + data.header);

                } else {
                    console.info('error:' + err.data);
                    prompt.showToast({
                        message: 'Hearten'+ JSON.stringify(err)
                    })
                }
            });
        this.$element('videohearten').animate(this.frames,this.options).play()
    },

//    滑板
    skate(){
        //正在滑板
        if(this.skating){
//            clearInterval(this.decodetimer)
            this.skating = false
            this.skateicon = '/common/picture/startskate.png'
//            this.unsubscribe()
            this.skatebottonvalue = '开始'
            clearInterval(this.timer);
            //保存上一次的行程id
            this.lasttripid = this.tripid;
        }
        //未开始滑板
        else{
            this.subscribe();
            this.skatebottonvalue = '结束'
            this.second = 0;
            this.minute = 0;
            this.hour = 0;
//            this.subscribe();
//            this.decodetimer = setInterval(()=>{
//                this.LLtransffer();
//                this.gaodedecode();
//            },3000);
            this.uploadTrip();
            this.timer = setInterval(()=>{
//                this.decode();
                //this.getLocation();
//                this.gaodedecode();
                this.second = this.second+1;
                if(this.second>=60){
                    this.minute=this.minute+1;
                    this.second = 0;
                    this.uploadLocation()
                }
                if(this.minute>=60){
                    this.hour = this.hour+1;
                    this.minute = 0
                }
                if(this.hour>=24){
                    clearInterval(this.timer)
                    this.skating = false
                    this.skateicon = '/common/picture/startskate.png'
                }
            }, 1000);
            this.skating = true
            this.skateicon = '/common/picture/endskate.png'
        }
    },
    uploadTrip(){
        let httpRequest= http.createHttp();
        httpRequest.request("http://101.35.82.76:9002/trip/addtrip?userid="+this.userid,
            {
                method: 'GET',
                readTimeout: 60000,
                connectTimeout: 60000
            },(err, data) => {
                if (!err) {
                    console.info('Result:' + data.result);
                    console.info('code:' + data.responseCode);
                    console.info('header:' + data.header);

                    var res = JSON.stringify(JSON.parse(data.result).data)
                    this.tripid = JSON.stringify(JSON.parse(res).tripid)

                } else {
                    console.info('error:' + err.data);
                    prompt.showToast({
                        message: 'Send Error'+ JSON.stringify(err)
                    })
                }
            });
    },
    uploadLocation(){
        if(this.tripid !== null &&
        this.ll !== '经纬度' &&
        this.location!=='地址'){
            prompt.showToast({
                message:"上传定位"
            })
            let httpRequest= http.createHttp();
            httpRequest.request("http://101.35.82.76:9002/trip/addlocation?tripid="+this.tripid+"&location="+this.ll+
                "&address="+this.location+"&userid="+this.userid,
                {
                    method: 'GET',
                    readTimeout: 60000,
                    connectTimeout: 60000
                },(err, data) => {
                    if (!err) {
                        console.info('Result:' + data.result);
                        console.info('code:' + data.responseCode);
                        console.info('header:' + data.header);

                    } else {
                        console.info('error:' + err.data);
                        prompt.showToast({
                            message: 'Send Error'+ JSON.stringify(err)
                        })
                    }
                });
        }
    },

//    地理
    InitLocation(){
        var that = this;
        geolocation.getLocation({
            success(data){
                that.longitude = data.longitude
                that.latitude = data.latitude
                //获取地址成功后转编码
                fetch.fetch({
                    url: 'https://restapi.amap.com/v3/assistant/coordinate/convert?coordsys=gps&output=json&key=98faeeb5978c4f2e4d97759de7eba5e8&locations='+that.longitude+','+that.latitude,
                    success: function(response) {
                        var locations = JSON.parse(response.data).locations
                        that.ll = locations
                        //转编码成功后逆编码
                        if(that.ll!=='' && that.ll!==null){
                            fetch.fetch({
                                url: 'https://restapi.amap.com/v3/geocode/regeo?key=98faeeb5978c4f2e4d97759de7eba5e8&location='+that.ll,
                                success: function(response) {
                                    console.info("fetch success");
                                    var regeocode = JSON.stringify(JSON.parse(response.data).regeocode)
                                    that.location = JSON.parse(regeocode).formatted_address//JSON.stringify()
                                },
                                fail: function() {
                                    console.info("fetch fail");
                                }
                            });
                        }
                    },
                    fail: function() {
                        console.info("fetch fail");
                    }
                });
            },
            fail: function(data, code) {
                console.log('fail to get location. code:' + code + ', data:' + data);
            },
        });
    },
//    获取本机GPS位置
    getLocation() {
        var _this = this;
        geolocation.getLocation({
            success(data){
                _this.longitude = data.longitude
                _this.latitude = data.latitude
//                prompt.showToast({
//                    message: data
//                })
            },
            fail: function(data, code) {
                console.log('fail to get location. code:' + code + ', data:' + data);
                prompt.showToast({
                    message: 'fail to get location. code:' + code + ', data:' + data,
                })
            },
        });
    },
//    订阅位置
    subscribe() {
        var _this = this;
        geolocation.subscribe({
            success: function(data) {
                _this.latitude = data.latitude;
                _this.longitude = data.longitude;

            },
            fail: function(data, code) {
                console.log('fail to get location. code:' + code + ', data:' + data);
            }
        });
    },
//    取消订阅位置
    unsubscribe() {
        geolocation.unsubscribe();
    },
//    decode(){
//        this.echo.decode(this.latitude,this.longitude)
//            .then((data) => {
//                this.location = data["abilityResult"];
//            });
//    },
//    高德api逆编码
    gaodedecode(){
        var url = 'https://restapi.amap.com/v3/geocode/regeo?key=98faeeb5978c4f2e4d97759de7eba5e8&location='+this.ll;
        var that = this;
        if(this.location!=='' && this.location!==null){
            fetch.fetch({
                url: url,
                success: function(response) {
                    console.info("fetch success");
                    var regeocode = JSON.stringify(JSON.parse(response.data).regeocode)
                    that.location = JSON.parse(regeocode).formatted_address//JSON.stringify()
                },
                fail: function() {
                    console.info("fetch fail");
                    that.location = '定位失败'
                    prompt.showToast({
                        message: '定位失败'
                    })
                }
            });
        }
    },
//    高德api GPS坐标系转换火星坐标系
    LLtransffer(){
        var url = 'https://restapi.amap.com/v3/assistant/coordinate/convert?coordsys=gps&output=json&key=98faeeb5978c4f2e4d97759de7eba5e8&locations='+this.longitude+','+this.latitude;
        var that = this;
        fetch.fetch({
            url: url,
            success: function(response) {
                console.info("fetch success");
                var locations = JSON.parse(response.data).locations
//                prompt.showToast({
//                    message: locations
//                })
                that.ll = locations
            },
            fail: function() {
                console.info("fetch fail");
                prompt.showToast({
                    message: '坐标转换失败'
                })
            }
        });
    },

//    文件
//    文件下载
    downloadVideo(){
        //internal://share/
        request.download({ url: this.videoid},
            (err, data) => {
                if (err) {
                    console.error('Failed to request the download. Cause: ' + JSON.stringify(err));
                    return;
                }
                prompt.showToast({
                    message: data
                })
                data.on('progress', this.download_callback);

            });
    },
    download_callback(receivedSize, totalSize) {
        console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize);
        var that = this;
        if(receivedSize>=totalSize){
            prompt.showToast({
                message: '开始复制'
            })
            this.utilInterface = createLocalParticleAbility('edu.zut.hys.jsskateboard.util.UtilServiceAbility');
            this.utilInterface.saveVideo('internal://cache/'+this.videoid,result => {
                console.info(this.lable+result)
            })
        }
    },
//    DownloadFile(){
//        this.picturename = 'wutiaowu.png'
////        'http://101.35.82.76:9001/file/picture?name=wutiaowu.png'
//        request.download({ url: 'http://101.35.82.76:9001/file/picture/'+this.picturename},
//            (err, data) => {
//            if (err) {
//                console.error('Failed to request the download. Cause: ' + JSON.stringify(err));
//                return;
//            }
//            prompt.showToast({
//                message: data
//            })
////            downloadTask = data;
//            data.on('progress', this.download_callback);
//        });
//
//    },
//    download_callback(receivedSize, totalSize) {
//        console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize);
//    },
//    文件上传
    UploadFile(){
        request.upload({ url: 'http://101.35.82.76:9001/upload',
            files:[{
            filename: this.picturename,
            name:'file',
            uri:'internal://cache/'+this.picturename,
            type:'jpg',
               }]
        },
            (err, data) => {
            prompt.showToast({
                message: JSON.stringify(data)
            })
            if (err) {
                prompt.showToast({
                    message: JSON.stringify(err)
                })
                console.error('Failed to request the upload. Cause: ' + JSON.stringify(err));
                return;
            }
            var uploadTask = data;
        });
    },
//    图片选择
    ChoosePicture(){
        var that = this
        let option = {type : "image", count : 1  };
        mediaLibrary.getMediaLibrary().startMediaSelect(option).then((value) => {
            console.log("Media resources selected."+value);             // Obtain the media selection value.
            // 使用calculate同步方法，返回OperateData对象。
            this.utilInterface = createLocalParticleAbility('edu.zut.hys.jsskateboard.util.UtilServiceAbility');
            this.utilInterface.CopyToCache(value[0],result => {
                that.picturename = result
                console.info(this.lable+result)
                prompt.showToast({
                    message: '选择成功'
                })
//                prompt.showToast({
//                    message: result
//                })
            })
        }).catch((err) => {
            prompt.showToast({
                message: '选择失败'
            })
            console.log("An error occurred when selecting media resources.");
        });
    },
//    cache下文件
    List() {
        var that = this
        file.list({
            uri: 'internal://cache/',
            success: function(data) {
                console.info(that.lable+JSON.stringify(data.fileList));
                prompt.showToast({
                    message: data.fileList
                })
            },
            fail: function(data, code) {
                console.error(that.lable+'call fail callback fail, code: ' + code + ', data: ' + data);
                prompt.showToast({
                    message: that.lable+'call fail callback fail, code: ' + code + ', data: ' + data
                })
            },
        });
    },
    TabChange(e){
        console.log("Tab index: " + e.index);
    },
    unFollow(msg){
        var touserid = `${msg.target.dataSet.touserid}`
        let httpRequest= http.createHttp();
        httpRequest.request("http://101.35.82.76:9002/follow/deleteFollow?userid=" +this.userid+'&touserid='+touserid,
            {
                method: 'GET',
                readTimeout: 60000,
                connectTimeout: 60000
            },(err, data) => {
                if (!err) {
                    console.info('Result:' + data.result);
                    console.info('code:' + data.responseCode);
                    console.info('header:' + data.header);

                } else {
                    console.info('error:' + err.data);
                    prompt.showToast({
                        message: 'upfollow Send Error'+ JSON.stringify(err)
                    })
                }
            });
    },
    skatepopupvis(e){
        this.skatepopup = e.visibility;
//        prompt.showToast({
//            message:e.visibility
//        })
    },
    openskatepopup(){
        this.$element("skate-popup").show();
    },
    closeskatepopup(){
        this.$element("skate-popup").hide();
    },
    historicalTrip(){
        router.push({
            uri: "pages/historytrippage/historytrippage",
            params: {}
        });
    },
    uploadPark(){
        router.push({
            uri: "pages/uploadparkpage/uploadparkpage",
            params: {}
        });
//        this.$element("skate-popup").hide();
    },
    LoadParks(){
        let httpRequest= http.createHttp();
        httpRequest.request("http://101.35.82.76:9002/park/getParks",
            {
                method: 'GET',
                readTimeout: 60000,
                connectTimeout: 60000
            },(err, data) => {
                if (!err) {
                    console.info('Result:' + data.result);
                    console.info('code:' + data.responseCode);
                    console.info('header:' + data.header);

                    var res = JSON.stringify(JSON.parse(data.result).data)
                    var parks = JSON.stringify(JSON.parse(res).parks)
                    this.parks = JSON.parse(parks)

                } else {
                    console.info('error:' + err.data);
                    prompt.showToast({
                        message: 'LoadParks Error'+ JSON.stringify(err)
                    })
                }
            });
    },
//    方法测试得到不符合预期结果
//    Access(){
//        fileio.access('internal://cache/'+e'wutiaowu.png')
//            .then(function(err) {
//                prompt.showToast({
//                    message: '文件存在'
//                })
//                console.info('文件存在')
//            }).catch(function(e) {
//            console.info('文件不存在')
//            prompt.showToast({
//                message: '文件不存在'
//            })
//        });
//    },
//    copy(src,dst) {
//        var that = this
//        file.copy({
//            srcUri: src,
//            dstUri: dst,//'internal://app/file_copy.txt',
//            success: function(uri) {
//                console.log(that.lable+'call success callback success'+uri);
//                that.list()
//            },
//            fail: function(data, code) {
//                console.error(that.lable+'call fail callback fail, code: ' + code + ', data: ' + data);
//            },
//        });
//    },

//    api6 mate30pro测试异常
//    async ChooseFile(){
//        await document.choose(["*"]).then((data)=>{
//            prompt.showToast({
//                message: data
//            })
//        })
//    },

}
